<script lang="ts" setup>
import type { FileInfo, ShareItem as ShareInfo } from '#/api/openapi';

import { computed, ref } from 'vue';

import { Close, Code } from '@icon-park/vue-next';

import Button from '#/components/fluentui/Button.vue';
import Dialog from '#/components/fluentui/Dialog.vue';
import DialogBody from '#/components/fluentui/DialogBody.vue';
import { copyShareCode } from '#/utils/copy';
import { getFileIcon } from '#/utils/icon';
import { formatTime } from '#/utils/time';

const props = withDefaults(
  defineProps<{
    modelValue?: boolean;
    shareInfo?: ShareInfo;
  }>(),
  {
    modelValue: false,
    shareInfo: undefined,
  },
);
const emit = defineEmits<{
  downloadAll: [code: string, files: FileInfo[]];
  downloadFile: [code: string, file: FileInfo];
  'update:modelValue': [value: boolean];
}>();
// 关闭对话框
const closeDialog = () => {
  isVisible.value = false;
};
// 响应式状态
const isVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value),
});

const selectedFiles = ref<Set<number | undefined>>(new Set());

// 计算属性
// const shareLink = computed(() => {
//   if (!props.shareInfo) return '';
//   return `${window.location.origin}/download/${props.shareInfo.code}`;
// });

const allSelected = computed(() => {
  if (!props.shareInfo?.files?.length) return false;
  return props.shareInfo.files.every((file) =>
    selectedFiles.value.has(file.id),
  );
});

const hasSelectedFiles = computed(() => {
  return selectedFiles.value.size > 0;
});

const selectedFilesList = computed(() => {
  if (!props.shareInfo) return [];
  return props.shareInfo.files?.filter((file) =>
    selectedFiles.value.has(file.id),
  );
});

// 格式化文件大小
const formatFileSize = (bytes: number | undefined): string => {
  if (bytes === undefined || bytes < 0) return '未知大小';
  if (bytes === 0) return '0 Bytes';
  const k = 1024;
  const sizes = ['Bytes', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return `${Number.parseFloat((bytes / k ** i).toFixed(2))} ${sizes[i]}`;
};

// 复制分享链接
// const copyShareLink = async () => {
//   try {
//     await copyText(shareLink.value, '分享链接已复制');
//     // 这里可以添加成功提示
//     console.log('分享链接已复制');
//   } catch (error) {
//     console.error('复制失败:', error);
//   }
// };

// 文件选择相关
const toggleFileSelection = (fileId: number | undefined) => {
  if (selectedFiles.value.has(fileId)) {
    selectedFiles.value.delete(fileId);
  } else {
    selectedFiles.value.add(fileId);
  }
  // 触发响应式更新
  selectedFiles.value = new Set(selectedFiles.value);
};

const toggleAllFiles = () => {
  if (!props.shareInfo) return;

  if (allSelected.value) {
    selectedFiles.value.clear();
  } else {
    selectedFiles.value = new Set(
      props.shareInfo.files?.map((file) => file.id),
    );
  }
};
const totalDownloadCount = computed(() => {
  if (!props.shareInfo) return 0;
  return props.shareInfo.files?.reduce(
    (sum, file) => sum + (file.downloadCount || 0),
    0,
  );
});
// 下载操作
const downloadFile = (file: FileInfo) => {
  emit('downloadFile', props.shareInfo?.code ?? '', file);
  // if (file.downloadCount) file.downloadCount++;
};

const downloadSelected = () => {
  if (!hasSelectedFiles.value) return;
  if (!selectedFilesList.value) return;
  emit('downloadAll', props.shareInfo?.code ?? '', selectedFilesList.value);

  // 更新下载计数
  // selectedFilesList.value?.forEach((file) => {
  // if (file.downloadCount) file.downloadCount++;
  // });
};

const downloadAll = () => {
  if (!props.shareInfo) return;
  if (!props.shareInfo.files) return;
  emit('downloadAll', props.shareInfo?.code ?? '', props.shareInfo.files);

  // // 更新下载计数
  // props.shareInfo.files?.forEach((file) => {
  //   if (file.downloadCount) file.downloadCount++;
  // });
};

// 关闭弹窗
const handleClose = () => {
  isVisible.value = false;
  selectedFiles.value.clear();
};

// 计算总文件大小
const totalSize = computed(() => {
  if (!props.shareInfo) return 0;
  return props.shareInfo.files?.reduce(
    (sum, file) => sum + (file.fileSize ?? 0),
    0,
  );
});

const selectedSize = computed(() => {
  return selectedFilesList.value?.reduce(
    (sum, file) => sum + (file.fileSize ?? 0),
    0,
  );
});
</script>

<template>
  <Dialog
    v-model="isVisible"
    type="modal"
    aria-labelledby="share-info-dialog-title"
  >
    <DialogBody>
      <div class="mx-auto w-full max-w-4xl">
        <!-- 标题区域 -->
        <div>
          <h2
            id="share-info-dialog-title"
            class="mb-2 flex justify-between text-2xl font-bold text-gray-900 dark:text-gray-100"
          >
            分享详情
            <Button appearance="subtle" icon-only @click="closeDialog">
              <Close />
            </Button>
          </h2>
          <div
            class="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between"
          >
            <div
              class="flex flex-col gap-4 text-sm text-gray-600 sm:flex-row dark:text-gray-400"
            >
              <div class="flex items-center gap-2">
                <div class="flex items-center">
                  <span class="font-medium">分享码：</span>
                  <Tooltip
                    content="点击复制分享码"
                    placement="top"
                    :delay="500"
                    :disabled="!shareInfo?.code"
                  >
                    <Button
                      size="small"
                      appearance="transparent"
                      @click="copyShareCode(shareInfo.code ?? '')"
                      class="rounded-xl p-1 hover:bg-green-100 dark:hover:bg-green-900/50"
                    >
                      <span
                        class="rounded bg-gray-100 px-2 py-1 font-mono dark:bg-gray-800"
                      >
                        {{ shareInfo?.code ?? '无分享码' }}
                      </span>
                      <div
                        class="ml-2 mr-1 flex flex-shrink-0 items-center justify-center"
                      >
                        <Code theme="outline" size="14" fill="currentColor" />
                      </div>
                    </Button>
                  </Tooltip>
                </div>
                <div>
                  <span class="font-medium">创建时间：</span>
                  {{ formatTime(shareInfo?.createTime) }}
                </div>
                <div v-if="shareInfo?.expiryTime">
                  <span class="font-medium">过期时间：</span>
                  {{ formatTime(shareInfo.expiryTime) }}
                </div>
              </div>
            </div>
          </div>
          <div
            v-if="shareInfo?.messages"
            class="mt-2 text-sm text-gray-600 dark:text-gray-400"
          >
            <span class="font-medium">
              消息：
              <span v-if="shareInfo.messages.length === 0">无信息</span>
            </span>
            <div class="mb-1 mt-1">
              <span v-for="(message, index) in shareInfo.messages" :key="index">
                <span class="ml-1">{{ message.content }}</span>
                <span class="ml-2 font-thin italic">{{
                  formatTime(message.createdAt)
                }}</span>
                <br v-if="index < shareInfo.messages.length - 1" />
              </span>
            </div>
          </div>

          <!-- 统计信息 -->
          <div class="mb-6 rounded-lg bg-gray-50 p-4 dark:bg-gray-800">
            <div class="grid grid-cols-2 gap-2 text-center sm:grid-cols-4">
              <div>
                <div class="text-2xl font-bold text-blue-600">
                  {{ shareInfo?.files?.length || 0 }}
                </div>
                <div class="text-sm text-gray-600 dark:text-gray-400">
                  总文件数
                </div>
              </div>
              <div>
                <div class="text-2xl font-bold text-green-600">
                  {{ formatFileSize(totalSize) }}
                </div>
                <div class="text-sm text-gray-600 dark:text-gray-400">
                  总大小
                </div>
              </div>
              <div>
                <div class="text-2xl font-bold text-orange-600">
                  {{ selectedFiles.size }}
                </div>
                <div class="text-sm text-gray-600 dark:text-gray-400">
                  已选择
                </div>
              </div>
              <div>
                <div class="text-2xl font-bold text-purple-600">
                  {{ totalDownloadCount }}
                </div>
                <div class="text-sm text-gray-600 dark:text-gray-400">
                  下载次数
                </div>
              </div>
            </div>
          </div>

          <!-- 操作按钮区域 -->
          <div class="mb-6 flex flex-col gap-3 sm:flex-row">
            <div class="flex gap-2">
              <Button appearance="outline" @click="toggleAllFiles">
                {{ allSelected ? '取消全选' : '全选' }}
              </Button>
              <Button
                appearance="primary"
                @click="downloadSelected"
                :disabled="!hasSelectedFiles"
              >
                下载选中 ({{ selectedFiles.size }})
                <span v-if="hasSelectedFiles" class="ml-1">
                  {{ formatFileSize(selectedSize) }}
                </span>
              </Button>
            </div>
            <div class="flex gap-2 sm:ml-auto">
              <Button @click="downloadAll"> 下载全部 </Button>
              <!-- <Button appearance="subtle" @click="copyShareLink">
                复制链接
              </Button> -->
            </div>
          </div>

          <!-- 文件列表 -->
          <div
            class="overflow-hidden rounded-lg border border-gray-200 dark:border-gray-700"
          >
            <!-- 表头 -->
            <div
              class="border-b border-gray-200 bg-gray-50 px-4 py-3 dark:border-gray-700 dark:bg-gray-800"
            >
              <div class="flex items-center">
                <CheckBox :checked="allSelected" @change="toggleAllFiles" />
                <span
                  class="ml-3 text-sm font-medium text-gray-700 dark:text-gray-300"
                >
                  文件名
                </span>
              </div>
            </div>

            <!-- 文件项 -->
            <div class="max-h-96 overflow-y-auto">
              <div
                v-for="file in shareInfo?.files || []"
                :key="file.id"
                class="flex items-center justify-between border-b border-gray-100 p-4 transition-colors hover:bg-gray-50 dark:border-gray-700 dark:hover:bg-gray-800"
              >
                <div class="flex min-w-0 flex-1 items-center">
                  <CheckBox
                    :checked="selectedFiles.has(file.id)"
                    @change="toggleFileSelection(file.id)"
                  />
                  <span class="ml-3 mr-3 text-2xl">
                    <component :is="getFileIcon(file.fileName)" />
                  </span>
                  <div class="min-w-0 flex-1">
                    <div
                      class="truncate text-sm font-medium text-gray-900 dark:text-gray-100"
                    >
                      {{ file.fileName }}
                    </div>
                    <div class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                      {{ formatFileSize(file.fileSize) }} ·
                      {{ file.uploadTime }}
                      <!-- <span v-if="file.description" class="ml-2">
                        · {{ file.description }}
                      </span> -->
                    </div>
                  </div>
                </div>
                <div class="ml-4 flex items-center gap-3">
                  <span class="text-xs text-gray-500 dark:text-gray-400">
                    下载: {{ file.downloadCount }} 次
                  </span>
                  <Button
                    appearance="primary"
                    size="small"
                    @click="downloadFile(file)"
                  >
                    下载
                  </Button>
                </div>
              </div>
            </div>
          </div>

          <!-- 底部操作区域 -->
          <div class="mt-6 flex justify-end">
            <Button appearance="subtle" @click="handleClose"> 关闭 </Button>
          </div>
        </div>
      </div>
    </DialogBody>
  </Dialog>
</template>

<style scoped>
/* 滚动条样式 */
.max-h-96::-webkit-scrollbar {
  width: 6px;
}

.max-h-96::-webkit-scrollbar-track {
  background: rgb(243 244 246);
}

.max-h-96::-webkit-scrollbar-thumb {
  background: rgb(209 213 219);
  border-radius: 3px;
}

.max-h-96::-webkit-scrollbar-thumb:hover {
  background: rgb(156 163 175);
}

.dark .max-h-96::-webkit-scrollbar-track {
  background: rgb(31 41 55);
}

.dark .max-h-96::-webkit-scrollbar-thumb {
  background: rgb(75 85 99);
}

.dark .max-h-96::-webkit-scrollbar-thumb:hover {
  background: rgb(107 114 128);
}
</style>
